package com.flca.frw.zk.comp;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import com.flca.frw.zk.helper.ListboxHelper;
import com.flca.frw.zk.util.IListboxProvider;

public class ManyToOneCtrl extends Window {

	private static final long serialVersionUID = -3826597789415472882L;

	private Object value;
	
	private IListboxProvider provider;

	private SelectWindowCtrl selectCtrl;
	
	public void updateView(Object aValue) 
	{
		value = aValue;
		Textbox tb = (Textbox) getFellow("idInput");
		tb.setValue(getValue(aValue, getPropertyNames()));
	}

	public Object getValue() 
	{
		return value;
	}
	
	public void setValue(Object aValue) {
		value = aValue;
	}
	
	
	public IListboxProvider getProvider() {
		return provider;
	}

	public void setProvider(IListboxProvider provider) {
		this.provider = provider;
	}

	public void onSelect() 
	{
		selectCtrl = (SelectWindowCtrl) Executions.createComponents("/comp/SelectWindow.zul", null, null);
		selectCtrl.addEventListener(eventName(), new SelectWinEventlistener());
		selectCtrl.setup(provider, eventName());
		try {
			selectCtrl.doModal();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

	private String getValue(Object aValue, String aPropNames) 
	{
		if (aValue != null) {
			try {
				return ListboxHelper.valuesToString(aValue, aPropNames);
			} catch (Exception e) {
				e.printStackTrace();//TODO
				return aValue.toString();
			}
		} else {
			return null;
		}
	}
	
//	private String getLabelNames() 
//	{
//		if (provider != null) {
//			return provider.getLabelNames();
//		} else {
//			return null;
//		}
//	}

	private String getPropertyNames() 
	{
		if (provider != null) {
			return provider.getPropertyNames();
		} else {
			return null;
		}
	}
	
	private void handleSelectWinEvent(Object aObject)
	{
		if (aObject != null) {
			setValue(aObject);
		}
		selectCtrl.detach();
		updateView(getValue());
	}
	
	class SelectWinEventlistener implements EventListener
	{
		public void onEvent(Event event) throws Exception {
			handleSelectWinEvent(event.getData());
		}
	}

	public String eventName() {
		return "onSelWin" + provider.getClass().getSimpleName();
	}
}
